package com.hgy.plugin.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hgy.plugin.security.exception.AuthcException;
import com.hgy.plugin.security.exception.AuthzException;

/**
 * Security助手类
 * 
 * @author alone
 *
 */
public class SecurityHelper {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SecurityHelper.class);
	
	/**
	 * 登陆
	 * @param username
	 * @param password
	 */
	public static void login(String username, String password)throws AuthcException{
		
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser != null){
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				LOGGER.error("login failure", e);
				throw new AuthcException(e);
			}
		}
	}
	
	/**
	 *  登出
	 */
	public static void logout(){
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser != null){
			currentUser.logout();
		}
	}
	
	/**
	 * 判断是否具有某权限
	 * 
	 * @param permissionName
	 */
	public static void hasPermisson(String permissionName) {
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser != null){
			if(!currentUser.isPermitted(permissionName)){
				throw new AuthzException();
			}
		}
	}
}
